import apis from '@/services/apis'
import { defineStore } from 'pinia'
import type { UserInfoType } from '@/services/types'
import { StoresEnum } from '@/enums'
import { isDiffNow } from '@/utils/ComputedTime.ts'
import { refreshTokenAndRetry } from '@/services/refreshToken.ts'

export const useUserStore = defineStore(StoresEnum.USER, () => {
  const userInfo = ref<Partial<UserInfoType>>({})
  const isSign = ref(false)
  const refreshTokenInterval = ref<NodeJS.Timeout | undefined>()

  const getUserDetailAction = () => {
    apis
      .getUserDetail()
      .then((res) => {
        userInfo.value = { ...userInfo.value, ...res }
      })
      .catch(() => {
        // 删除缓存
        localStorage.removeItem('TOKEN')
        localStorage.removeItem('REFRESH_TOKEN')
      })
  }

  const setRefreshTokenInterval = () => {
    // 定时刷新 TOKEN (每3个小时更新一次)
    refreshTokenInterval.value = setInterval(async () => {
      const loginTime = localStorage.getItem('LOGIN_TIME')
      if (loginTime) {
        if (isDiffNow({ time: loginTime, unit: 'hour', diff: 3 })) {
          await refreshTokenAndRetry()
        }
      } else {
        clearInterval(refreshTokenInterval.value)
      }
    }, 3 * 60 * 60 * 1000)
  }

  watch(
    () => userInfo,
    (val) => {
      console.log('用户信息发生改变', val)
    }
  )

  return {
    userInfo,
    isSign,
    getUserDetailAction,
    setRefreshTokenInterval,
    refreshTokenInterval,
  }
})
